package com.ilink.groundservice.service.impl.InnovationPlaza;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ilink.groundservice.entity.PO.innovationPlaza.InnovationConnectTags;
import com.ilink.groundservice.entity.PO.innovationPlaza.InnovationPlaza;
import com.ilink.groundservice.entity.PO.innovationPlaza.InnovationPlazaImage;
import com.ilink.groundservice.entity.PO.innovationPlaza.InnovationTags;
import com.ilink.groundservice.entity.PO.innovationPlaza.ProjectConnectImage;
import com.ilink.groundservice.entity.PO.innovationPlaza.ProjectMetadata;
import com.ilink.groundservice.entity.PO.innovationPlaza.ProjectUser;
import com.ilink.groundservice.entity.VO.innovationPlaza.ProjectResponse;
import com.ilink.groundservice.entity.VO.innovationPlaza.ProjectdetailsIntroduceResponse;
import com.ilink.groundservice.entity.VO.innovationPlaza.ProjectdetailsMetaResponse;
import com.ilink.groundservice.mapper.innovationPlaza.InnovationConnectTagsMapper;
import com.ilink.groundservice.mapper.innovationPlaza.InnovationPlazaImageMapper;
import com.ilink.groundservice.mapper.innovationPlaza.InnovationPlazaMapper;
import com.ilink.groundservice.mapper.innovationPlaza.InnovationTagsMapper;
import com.ilink.groundservice.mapper.innovationPlaza.ProjectConnectImageMapper;
import com.ilink.groundservice.mapper.innovationPlaza.ProjectMetadataMapper;
import com.ilink.groundservice.mapper.innovationPlaza.ProjectUserMapper;
import com.ilink.ilinkapi.dto.ground.project.ProjectMetadataRequest;
import com.ilink.ilinkapi.dto.ground.project.dataload.MemberDTO;
import com.ilink.ilinkapi.dto.ground.project.dataload.ProjectData678DTO;
import com.ilink.ilinkapi.dto.ground.project.dataload.ProjectDataDTO;
import com.ilink.ilinkapi.dto.ground.project.dataload.TeacherDTO;
import com.ilink.ilinkapi.dto.ground.project.dataload.UserDTO;
import com.ilink.ilinkcommon.service.oss.OssService;
import com.ilink.ilinkcommon.utils.SnowflakeIdGenerator;
import java.math.BigInteger;
import java.util.Comparator;
import java.util.List;
import java.util.Objects;
import java.util.Optional;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.CacheConfig;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

@Service
@RequiredArgsConstructor
@CacheConfig(cacheNames = "innovation_project")
public class ProjectServiceImpl implements
    com.ilink.groundservice.service.InnovationPlaza.ProjectService {

    private final SnowflakeIdGenerator idGenerator = new SnowflakeIdGenerator(2, 2);

    @Autowired
    private ProjectMetadataMapper projectMetadataMapper;

    @Autowired
    private OssService ossService;

    @Autowired
    private ProjectConnectImageMapper projectConnectImageMapper;

    @Autowired
    private InnovationPlazaImageMapper innovationPlazaImageMapper;

    @Autowired
    private InnovationTagsMapper innovationTagsMapper;

    @Autowired
    private InnovationConnectTagsMapper innovationConnectTagsMapper;

    @Autowired
    private ProjectUserMapper projectUserMapper;

    @Autowired
    private InnovationPlazaMapper innovationPlazaMapper;

    @Override
    public List<InnovationTags> getCommonTags() {
        return innovationTagsMapper.selectCommonProjectTags();
    }

    /**
     * @return com.baomidou.mybatisplus.core.metadata.IPage<com.ilink.groundservice.entity.VO.innovationPlaza.ProjectResponse>
     * @Author Black Curry
     * @Description 条件分页查询项目展示列表; redis 添加缓存 注意如果更新了项目展示或者赛事信息表时需要清空相关缓存，不然查询出来的有问题
     * @Date 19:06 2024/9/29
     * @Param [request]
     **/
    @Override
//    @Cacheable(key = "#request", unless = "#result == null")
    public IPage<ProjectResponse> getALLProjects(ProjectMetadataRequest request) {
        // 1. 设置查询条件
        QueryWrapper<ProjectMetadata> queryWrapper = new QueryWrapper<>();

        Optional.ofNullable(request.getProjectStyle())
            .ifPresent(style -> queryWrapper.eq("project_style", style));
//        Optional.ofNullable(request.getSentence()).filter(s -> !s.isEmpty())
//            .ifPresent(sentence -> queryWrapper.like("name", sentence));

        // 关键词查询逻辑
        Optional.ofNullable(request.getSentence()).filter(s -> !s.isEmpty()).ifPresent(sentence -> {
            // 获取与关键词匹配的所有标签对应的 projectId
            List<Long> matchingProjectIds = innovationConnectTagsMapper.selectList(
                new LambdaQueryWrapper<InnovationConnectTags>()
                    .inSql(InnovationConnectTags::getTagId,
                        "SELECT tag_id FROM innovation_tags WHERE name LIKE '%" + sentence + "%'")
            ).stream().map(InnovationConnectTags::getProjectId).collect(Collectors.toList());

            // 如果匹配到标签对应的 projectId，则将其加入查询条件
            queryWrapper.and(wrapper -> wrapper
                .like("name", sentence)  // 根据标题匹配关键词
                .or()
                .like("description", sentence)  // 根据描述匹配关键词
                .or()
                .in(!matchingProjectIds.isEmpty(), "project_id", matchingProjectIds)  // 匹配标签对应的项目ID
            );
        });

        if (request.getTags() != null && !request.getTags().isEmpty()) {
            List<Long> projectIds = innovationTagsMapper.getProjectIdsByTags(request.getTags());
            if (projectIds.isEmpty()) {
                return new Page<>(request.getPageNum(), request.getPageSize(), 0);
            }
            queryWrapper.in("project_id", projectIds);
        }

        // 2. 获取总记录数
        long totalRecords = projectMetadataMapper.selectCount(queryWrapper);

        // 3. 获取分页的项目数据
        Page<ProjectMetadata> pageRequest = new Page<>(request.getPageNum(), request.getPageSize());
        IPage<ProjectMetadata> projectMetadataPage = projectMetadataMapper.selectPage(pageRequest,
            queryWrapper);

        // 4. 使用 CompletableFuture 简化并行处理
        List<CompletableFuture<ProjectResponse>> futures = projectMetadataPage.getRecords().stream()
            .map(projectMetadata -> CompletableFuture.supplyAsync(() -> {
                ProjectResponse projectResponse = new ProjectResponse();
                projectResponse.setProjectId(projectMetadata.getProjectId());
                projectResponse.setName(projectMetadata.getName());
                projectResponse.setCreatedTime(projectMetadata.getCreatedTime());
                projectResponse.setProjectStyle(
                    Optional.ofNullable(projectMetadata.getProjectStyle()).orElse(0));
                projectResponse.setDescription(projectMetadata.getDescription());
                projectResponse.setLikeNum(projectMetadata.getLikeNum());
                projectResponse.setShareNum(projectMetadata.getShareNum());
                projectResponse.setLookNum(projectMetadata.getLookNum());

                // 获取标签信息
                projectResponse.setTags(
                    innovationTagsMapper.getTagsByProjectId(projectMetadata.getProjectId()));

                // 设置图片路径
                projectResponse.setImage(Optional.ofNullable(projectMetadata.getProjectImage())
                    .map(ossService::getFileUrl).orElse(""));

                // 获取项目的其他图片
                List<String> projectImages = projectConnectImageMapper.getImageIdsByProjectId(
                        projectMetadata.getProjectId()).stream()
                    .map(imageId -> innovationPlazaImageMapper.selectById(imageId).getImage())
                    .filter(Objects::nonNull)
                    .map(ossService::getFileUrl)
                    .collect(Collectors.toList());
                projectResponse.setProjectImages(projectImages);

                return projectResponse;
            })).collect(Collectors.toList());

        // 5. 收集并等待所有并行任务完成
        List<ProjectResponse> projectResponses = futures.stream()
            .map(CompletableFuture::join)
            .collect(Collectors.toList());

        // 6. 根据需求进行排序
        Comparator<ProjectResponse> comparator = Comparator.comparing(
            ProjectResponse::getCreatedTime).reversed();
        if ("likenum".equalsIgnoreCase(request.getSortBy())) {
            comparator = Comparator.comparing(ProjectResponse::getLikeNum).reversed();
        } else if ("sharenum".equalsIgnoreCase(request.getSortBy())) {
            comparator = Comparator.comparing(ProjectResponse::getShareNum).reversed();
        } else if ("looknum".equalsIgnoreCase(request.getSortBy())) {
            comparator = Comparator.comparing(ProjectResponse::getLookNum).reversed();
        }
        projectResponses.sort(comparator);

        // 7. 构建最终分页结果
        Page<ProjectResponse> finalPage = new Page<>(request.getPageNum(), request.getPageSize(),
            totalRecords);
        finalPage.setRecords(projectResponses);

        return finalPage;
    }

    @Override
    public ProjectdetailsMetaResponse getProjectDetailsMeta(Long projectId) {
        ProjectdetailsMetaResponse response = new ProjectdetailsMetaResponse();

        // 获取项目名称
        String projectName = projectMetadataMapper.getProjectNameById(projectId);
        response.setName(projectName);

        // 获取项目标签
        List<String> tags = innovationTagsMapper.getTagsByProjectId(projectId);
        response.setTags(tags);

        // 获取项目风格
        Integer projectStyle = projectMetadataMapper.getProjectStyleById(projectId);
        response.setProjectStyle(String.valueOf(projectStyle));

        // 根据项目风格设置不同的字段
        if (projectStyle != null) {
            switch (projectStyle) {
                case 1:
                case 5:
                    // 获取口号
                    String advertise = projectMetadataMapper.getSloganByProjectId(projectId);
                    response.setAdvertise(advertise);
                    break;
                case 2:
                    // 获取公司名称
                    String company = projectMetadataMapper.getCompanyByProjectId(projectId);
                    response.setCompany(company);
                    break;
                case 3:
                    // 获取推荐人信息
                    String introductors = projectMetadataMapper.getIntroductorsByProjectId(
                        projectId);
                    response.setIntroductors(introductors);
                    break;
                case 4:
                    // 获取推荐人信息
                    String exhibitionCode = projectMetadataMapper.getExhibitionCodeByProjectId(
                        projectId);
                    response.setExhibitionCode(exhibitionCode);
                    break;
                default:
                    // 处理其他可能的风格值
                    break;
            }
        }

        return response;
    }

    public ProjectdetailsIntroduceResponse getProjectIntroduce(Long projectId) {
        ProjectMetadata projectMetadata = projectMetadataMapper.getdetialProjectItroduce(projectId);

        ProjectdetailsIntroduceResponse response = new ProjectdetailsIntroduceResponse();

        // 设置公共字段
        response.setIntroduction(projectMetadata.getIntroduction());

        Integer projectStyle = projectMetadata.getProjectStyle();

        // 根据 projectStyle 填充不同的字段
        if (projectStyle != null) {
            switch (projectStyle) {
                case 1:
                case 5:
                    // 获取 imageIds
                    List<Long> imageIds = projectConnectImageMapper.getImageIdsByProjectId(
                        projectId);

                    if (imageIds == null || imageIds.isEmpty()) {
                        System.out.println("No image IDs found for project ID: " + projectId);
                    } else {
                        System.out.println("Found image IDs: " + imageIds);
                    }

                    // 使用 imageIds 获取项目图片
                    List<String> projectImages = imageIds.stream()
                        .map(imageId -> {
                            String imagePath = innovationPlazaImageMapper.selectById(imageId)
                                .getImage();
                            if (imagePath == null || imagePath.isEmpty()) {
                                System.out.println(
                                    "Empty or null image path for image ID: " + imageId);
                                return null;
                            }
                            return imagePath;
                        })
                        .filter(Objects::nonNull)
                        .map(imageRelativePath -> {
                            String url = ossService.getFileUrl(imageRelativePath);
                            if (url == null) {
                                System.out.println(
                                    "Generated URL is null for path: " + imageRelativePath);
                            }
                            return url;
                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                    response.setProjectImages(projectImages);
                    response.setInnovation(projectMetadata.getInnovation());
                    break;
                case 2:
                    response.setDirectionField(projectMetadata.getDirectionField());
                    response.setDirectionTechnical(projectMetadata.getDirectionTechnical());
                    response.setResources(projectMetadata.getResources());
                    response.setSubmissionMaterials(projectMetadata.getSubmissionMaterials());
                    response.setEvaluationMethod(projectMetadata.getEvaluationMethod());
                    response.setSupportMatching(projectMetadata.getSupportMatching());
                    response.setSupportPolicy(projectMetadata.getSupportPolicy());
                    break;
                case 3:
                    response.setIconicResults(projectMetadata.getIconicResults());
                    response.setChallenge(projectMetadata.getChallenge());
                    response.setUndergraduatesAchievement(
                        projectMetadata.getUndergraduatesAchievement());
                    break;
                case 4:
                    response.setInnovation(projectMetadata.getInnovation());
                    response.setValue(projectMetadata.getValue());
                    response.setTeam(projectMetadata.getTeam());
                    List<Long> imageIds2 = projectConnectImageMapper.getImageIdsByProjectId(
                        projectId);

                    if (imageIds2 == null || imageIds2.isEmpty()) {
                        System.out.println("No image IDs found for project ID: " + projectId);
                    } else {
                        System.out.println("Found image IDs: " + imageIds2);
                    }

                    // 使用 imageIds 获取项目图片
                    List<String> projectImages2 = imageIds2.stream()
                        .map(imageId -> {
                            String imagePath = innovationPlazaImageMapper.selectById(imageId)
                                .getImage();
                            if (imagePath == null || imagePath.isEmpty()) {
                                System.out.println(
                                    "Empty or null image path for image ID: " + imageId);
                                return null;
                            }
                            return imagePath;
                        })
                        .filter(Objects::nonNull)
                        .map(imageRelativePath -> {
                            String url = ossService.getFileUrl(imageRelativePath);
                            if (url == null) {
                                System.out.println(
                                    "Generated URL is null for path: " + imageRelativePath);
                            }
                            return url;
                        })
                        .filter(Objects::nonNull)
                        .collect(Collectors.toList());

                    response.setProjectImages(projectImages2);
                    break;
                default:
                    // 处理其他可能的风格值
                    break;
            }
        }

        return response;
    }

    public List<ProjectUser> getProjectMembers(Long projectId) {
        return projectUserMapper.getProjectMembersByProjectId(projectId);
    }



    @Override
    public void insertProjectData(ProjectDataDTO projectDataDTO) {
        // Generate projectId using Snowflake ID generator
        Long projectId = idGenerator.nextId();

        // Insert into innovationPlaza with project type 'project'
        InnovationPlaza innovationPlaza = new InnovationPlaza();
        innovationPlaza.setProjectId(projectId);
        innovationPlaza.setProjectType(InnovationPlaza.ProjectType.project.name()); // 将枚举类型转换为字符串
        innovationPlazaMapper.insert(innovationPlaza);

        // Insert into project_metadata using the same projectId
        ProjectMetadata projectMetadata = new ProjectMetadata();
        projectMetadata.setProjectId(projectId); // Reuse the projectId from innovationPlaza
        projectMetadata.setIntroduction(projectDataDTO.getIntroduction().getWords());
        projectMetadata.setInnovation(projectDataDTO.getInnovation().getWords());
        projectMetadata.setName(projectDataDTO.getProjectName());
        projectMetadata.setProjectImage(projectDataDTO.getProjectImage());
        projectMetadata.setExhibitionCode(projectDataDTO.getExhibitionCode());
        projectMetadata.setValue(projectDataDTO.getValue().getWords());
        projectMetadata.setTeam(projectDataDTO.getTeam().getWords());
        projectMetadata.setProjectStyle(5);
        projectMetadataMapper.insert(projectMetadata);

        // Insert into innovation_connect_tags
        InnovationConnectTags innovationConnectTags = new InnovationConnectTags();
        innovationConnectTags.setProjectId(projectId); // Use the same projectId
        innovationConnectTags.setTagId(Long.parseLong(projectDataDTO.getTag()));
        innovationConnectTagsMapper.insert(innovationConnectTags);

        // Insert into project_user for members
        for (MemberDTO member : projectDataDTO.getMembers()) {
            ProjectUser projectUser = new ProjectUser();
            projectUser.setProjectId(BigInteger.valueOf(projectId)); // Use the same projectId
            projectUser.setParticipantId(BigInteger.valueOf(idGenerator.nextId())); // Generate new participantId
            projectUser.setUserType("项目成员");
            projectUser.setUserName(member.getMemberName());
            projectUser.setUserGrade(member.getGrade());
            projectUser.setUserCollege(member.getSchool());
            projectUser.setUserImage("http://study-square-migrate.oss-cn-beijing.aliyuncs.com/study-square-migrate/111/111_1724588048722.png?Expires=1724674448&OSSAccessKeyId=LTAI5tCCTsonpzgbA5od9dX1&Signature=PgERDrPmnwXotcYwNhGHNDXYNgk%3D");
            projectUserMapper.insert(projectUser);
        }

        // Insert into project_user for teachers
        for (TeacherDTO teacher : projectDataDTO.getTeachers()) {
            ProjectUser projectUser = new ProjectUser();
            projectUser.setProjectId(BigInteger.valueOf(projectId)); // Use the same projectId
            projectUser.setParticipantId(BigInteger.valueOf(idGenerator.nextId())); // Generate new participantId
            projectUser.setUserType("指导老师");
            projectUser.setUserName(teacher.getTeacherName());
            projectUser.setUserCollege(teacher.getTeacherSchool());
            projectUser.setUserGrade(null); // No grade for teachers
            projectUser.setUserImage("http://study-square-migrate.oss-cn-beijing.aliyuncs.com/study-square-migrate/111/111_1724588048722.png?Expires=1724674448&OSSAccessKeyId=LTAI5tCCTsonpzgbA5od9dX1&Signature=PgERDrPmnwXotcYwNhGHNDXYNgk%3D");
            projectUserMapper.insert(projectUser);
        }

        // Insert into innovationPlaza_image and project_connect_image
        for (String imagePath : projectDataDTO.getImages()) {
            Long imageId = idGenerator.nextId();

            // Insert into innovationPlaza_image
            InnovationPlazaImage innovationPlazaImage = new InnovationPlazaImage();
            innovationPlazaImage.setImageId(imageId);
            innovationPlazaImage.setImage(imagePath);
            innovationPlazaImageMapper.insert(innovationPlazaImage);

            // Insert into project_connect_image
            ProjectConnectImage projectConnectImage = new ProjectConnectImage();
            projectConnectImage.setProjectId(projectId); // Use the same projectId
            projectConnectImage.setImageId(imageId);
            projectConnectImageMapper.insert(projectConnectImage);
        }
    }

    @Override
    public void insertProjectData678(ProjectData678DTO projectData678DTO) {
        Long projectId = idGenerator.nextId();
        InnovationPlaza innovationPlaza = new InnovationPlaza();
        innovationPlaza.setProjectId(projectId);
        innovationPlaza.setProjectType(InnovationPlaza.ProjectType.project.name()); // 枚举转字符串
        innovationPlazaMapper.insert(innovationPlaza);

        // Insert into project_metadata using the same projectId
        ProjectMetadata projectMetadata = new ProjectMetadata();
        projectMetadata.setProjectId(projectId);
        projectMetadata.setAdvertise(projectData678DTO.getAdvertise());
        projectMetadata.setIntroduction(projectData678DTO.getIntroduction());
        projectMetadata.setInnovation(projectData678DTO.getInnovation());
        projectMetadata.setName(projectData678DTO.getName());
        projectMetadata.setProjectImage("yanchuang678/"+projectData678DTO.getProjectImage());
        projectMetadata.setDescription(projectData678DTO.getDescription());
        projectMetadata.setProjectStyle(6);
        projectMetadataMapper.insert(projectMetadata);


        for (String tagName : projectData678DTO.getTaps()) {
            // 插入标签
            Long tagId = idGenerator.nextId();
            InnovationTags innovationTags = new InnovationTags();
            innovationTags.setTagId(tagId);
            innovationTags.setName(tagName);
            innovationTags.setTagType(InnovationPlaza.ProjectType.project.name());
            innovationTagsMapper.insert(innovationTags);

            // 插入关联表
            InnovationConnectTags innovationConnectTags = new InnovationConnectTags();
            innovationConnectTags.setProjectId(projectId);
            innovationConnectTags.setTagId(innovationTags.getTagId());
            innovationConnectTagsMapper.insert(innovationConnectTags);
        }

        for (String imagePath : projectData678DTO.getImages()) {
            Long imageId = idGenerator.nextId();

            // 插入图片
            InnovationPlazaImage innovationPlazaImage = new InnovationPlazaImage();
            innovationPlazaImage.setImageId(imageId);
            innovationPlazaImage.setImage("yanchuang678/"+imagePath);
            innovationPlazaImageMapper.insert(innovationPlazaImage);

            // 插入关联表
            ProjectConnectImage projectConnectImage = new ProjectConnectImage();
            projectConnectImage.setProjectId(projectId);
            projectConnectImage.setImageId(imageId);
            projectConnectImageMapper.insert(projectConnectImage);
        }

        for (UserDTO user : projectData678DTO.getUsers()) {
            Long userId = idGenerator.nextId();
            ProjectUser projectUser = new ProjectUser();
            projectUser.setProjectId(BigInteger.valueOf(projectId)); // 使用项目ID
            projectUser.setParticipantId(BigInteger.valueOf(userId)); // 生成参与者ID
            projectUser.setUserName(user.getUserName());
            projectUser.setUserCollege(user.getUserCollege());
            projectUser.setUserIntroduction(user.getUserIntroduction());
            projectUser.setUserGrade(user.getUserGrade());
            projectUser.setUserMajor(user.getUserMajor());
            projectUser.setUserType(user.getUserType()); // 项目成员或指导老师
            projectUser.setUserImage("http://study-square.oss-cn-beijing.aliyuncs.com/study-square/111/111_1724588048722.png?Expires=1724674448&OSSAccessKeyId=LTAI5tCCTsonpzgbA5od9dX1&Signature=PgERDrPmnwXotcYwNhGHNDXYNgk%3D"); // 可以指定默认图片或根据需求设置
            projectUserMapper.insert(projectUser);
        }



    }

}
